# -*- coding: utf-8 -*-

#    This file is part of pyCorreios.
#    
#    pyCorreios is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    
#    pyCorreios is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    
#    You should have received a copy of the GNU General Public License
#    along with pyCorreios.  If not, see <http://www.gnu.org/licenses/>.


#
# IMPORTS
#
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import os
from threading import Lock
from data import Data

#
# CONSTANTS
#
UPDATE_INTERVAL=60000

#
# CODE
#
class GUI(object):
    
    def __init__(self):
        # Data
        self.__data = Data()
        
        # Mutex
        self.__mutex = Lock()
        
        self.__mutex.acquire()
        
        # Buttons
        self.add_button = gtk.Button(stock=gtk.STOCK_ADD)
        self.add_button.connect('clicked', self.add_button_clicked)
        self.add_button.show()
        
        self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE)
        self.remove_button.set_sensitive(False)
        self.remove_button.connect('clicked', self.remove_button_clicked)
        self.remove_button.show()
        
        self.about_button = gtk.Button(stock=gtk.STOCK_HELP)
        self.about_button.show()
        
        self.close_button = gtk.Button(stock=gtk.STOCK_CLOSE)
        self.close_button.connect('clicked', self.close_button_clicked)
        self.close_button.show()        

        # Button Box
        button_box = gtk.VBox(homogeneous=False, spacing=2)
        button_box.pack_start(self.add_button, False, False, 0)
        button_box.pack_start(self.remove_button, False, False, 0)
        button_box.pack_end(self.close_button, False, False, 0)
        button_box.pack_end(self.about_button, False, False, 0)
        button_box.show()
        
        # Main Display
        self.list = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
        self.treeview = gtk.TreeView(self.list)

        columns = [
            gtk.TreeViewColumn('Código da Encomenda'),
            gtk.TreeViewColumn('Última Atualização'),
            gtk.TreeViewColumn('Local'),
            gtk.TreeViewColumn('Status')
        ]

        # add columns to treeview
        for i in range(len(columns)):
            column = columns[i]
            self.treeview.append_column(column)
            cell = gtk.CellRendererText()
            column.pack_start(cell, True)
            column.set_attributes(cell, text=i)
        
        self.treeview.connect('cursor-changed', self.change_row)
        self.treeview.show()
        
        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled_window.add_with_viewport(self.treeview)
        scrolled_window.show()

        
        # Content Box
        content_box = gtk.HBox(homogeneous=False, spacing=2)
        content_box.pack_start(scrolled_window, True, True, 0)
        content_box.pack_start(button_box, False, False, 0)
        content_box.show()        
        
        # Set up main window
        self.__window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.__window.set_title('pyCorreios')
        self.__window.set_icon_from_file("../svg/icon_64x64.svg")
        self.__window.connect("destroy", self.destroy)
        self.__window.add(content_box)
        self.__window.set_default_size(800, 400)
        self.__window.show()
        
        # Create dialog for new tracking code
        self.newtrack_dialog = gtk.Dialog("Adicionar uma encomenda",
                     self.__window,
                     gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                     (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                      gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        label = gtk.Label('Digite o código de rastreio dos Correios:')
        label.show()
        self.newtrack_input = gtk.Entry(max=18)
        self.newtrack_input.show()
        
        self.newtrack_dialog.vbox.pack_start(label, False, False, 0)
        self.newtrack_dialog.vbox.pack_start(self.newtrack_input, False, False, 0)
        self.newtrack_dialog.connect('response', self.newtrack_response)
        
        # Insert rows
        for code in self.__data.getCodes():
            self.list.append([code, '?', '?', '?'])
            
        # Update rows in background
        gobject.timeout_add(100, self.background_update)         
        
        # Set-up timer
        gobject.timeout_add(UPDATE_INTERVAL, self.timeout)
        
        self.__mutex.release() 
        
    
    def run(self):
        gtk.main()
        
    def timeout(self):
        self.__mutex.acquire()
        self.__update()
        self.__mutex.release()
        return True
        
    def background_update(self):
        self.__mutex.acquire()
        self.__update()
        self.__mutex.release()
        return False
    
    def change_row(self, treeview, data = None):
        ((row_number,), col) = treeview.get_cursor()
        if row_number >= 0:
            selection = treeview.get_selection()
            model, iter = selection.get_selected()
            if iter:
                self.remove_button.set_sensitive(True)
        
    def newtrack_response(self, dialog, response_id, data = None):
        if response_id == gtk.RESPONSE_ACCEPT:
            self.__mutex.acquire()
            code = self.newtrack_input.get_text()
            if not code in self.__data.getCodes():
                self.list.append([code, '?', '?', '?'])
                self.__data.add(code)
                gobject.timeout_add(100, self.background_update)
            self.__mutex.release()
            
        self.newtrack_dialog.hide()
        
    def add_button_clicked(self, data = None):
        self.newtrack_input.set_text("")
        self.newtrack_dialog.show()
        
    def remove_button_clicked(self, data = None):
        self.__mutex.acquire()
        selection = self.treeview.get_selection()
        model, iter = selection.get_selected()
        if iter:
            code = model.get_value(iter, 0) 
            self.__data.remove(code)
            model.remove(iter)
                    
        self.remove_button.set_sensitive(False)
        self.__mutex.release()
        
    def close_button_clicked(self, data = None):
        self.__window.destroy()
    
    def destroy(self, widget, data=None):
        gtk.main_quit()    
    
    def __update(self):
        self.__data.update()
        iter = self.list.get_iter_root()
        while iter != None:
            code = self.list.get_value(iter, 0) 
            row_info = self.__data.get(code)
            if len(row_info) > 0:
                last_update = row_info[0]
                if len(last_update) > 1:
                    self.list.set_value(iter, 1, last_update[0])
                    self.list.set_value(iter, 2, last_update[1])
                if len(last_update) > 3:
                    self.list.set_value(iter, 3, last_update[3])
                elif len(last_update) > 2:
                    self.list.set_value(iter, 3, last_update[2])
            iter = self.list.iter_next(iter)
        

if __name__ == "__main__":
    gui = GUI()
    gui.run()
    
    